package geoapi

import (
	"encoding/json"
	"errors"
	"io/ioutil"
	"net/http"
)

type sogouResp []string

func GeoSogou(host string) (ig IPGeo, err error) {
	uri := `https://www.sogou.com/reventondc/external?type=2&charset=utf8&objid=20099801&p_ip=` + host
	req, err := http.NewRequest("GET", uri, nil)
	if err != nil {
		return
	}
	req.Header.Set("Referer", "https://www.sogou.com")

	c := &http.Client{}
	resp, err := c.Do(req)
	if err != nil {
		return
	}
	defer resp.Body.Close()
	data, err := ioutil.ReadAll(resp.Body)
	if err != nil {
		return
	}
	var t sogouResp
	err = json.Unmarshal(data, &t)
	if len(t) != 5 {
		err = errors.New("invalid response")
	}
	ig.CountryName = t[0]
	ig.CountryCode = getCountryCode(t[0])
	ig.City = t[1]
	ig.Isp = t[4]
	ig.Query = host
	ig.Status = "success"
	return
}
